define(['moment', 'sortablejs'], function (moment, Sortable) {
    return ['$scope', '$filter', '$stateParams', '$mdDialog', 'config', 'MMWService', '$calculater', '$datePicker', '$timeout', "$state",
    function ($scope, $filter, $stateParams, $mdDialog, config, $MMWService, $calculater, $datePicker, $timeout, $state) {
        $scope.Mode = '';
        $scope.machineList = [];//區域內的機台列表
        $scope.machine_detail = [];
        $scope.PageConfig = {page : 0, page_count : 25};
        $scope.dispatch_filter = {};
        $scope.is_lock_sort = false;
        $scope.select_all_bool = false;
        $scope.roll_back_all_bool = false;
        $scope.order_by_mode = {name:"",sort:false};
        $scope.assigned_machine = ''; // 過濾已派工的設備編號或設備名稱
        $scope.acc_detail = [];
        $scope.ht_tr_bool = false; //M#95547 add by a991241234 熱處理 是否顯示爐量

        $scope.equipment_sort_option_list = 
        [{label:$filter('translate')('A02.equipment_sort_list.option_0'),code:"0"},
        {label:$filter('translate')('A02.equipment_sort_list.option_1'),code:"1"},
        {label:$filter('translate')('A02.equipment_sort_list.option_2'),code:"2"},
        {label:$filter('translate')('A02.equipment_sort_list.option_3'),code:"3"},
        {label:$filter('translate')('A02.equipment_sort_list.option_4'),code:"4"},
        {label:$filter('translate')('A02.equipment_sort_list.option_5'),code:"5"},
        {label:$filter('translate')('A02.equipment_sort_list.option_6'),code:"6"},
        {label:$filter('translate')('A02.equipment_sort_list.option_7'),code:"7"}]

        $scope.equipment_sort_mode_label = $scope.equipment_sort_option_list[0].label;
        $scope.equipment_sort_mode = $scope.equipment_sort_option_list[0].code;
        $scope.equipment_sort_mode_change = false;
        $scope.product_detail = [];

        // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
        $scope.area_detail = [];
        $scope.selectareaNo = "";
        $scope.isLine = "";
        $scope.selectWorkStation = '';
        $scope.selectWorkStationName = '';

        $scope.init = function(){
            // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
            $scope.showMode = "query"
            $scope.printList = []; // 列印詳情

            $MMWService.PNIGList = {};
            $scope.work_date = new Date();//工作時間
            $scope.order_by_mode = {name:"",sort:false};
            // 20201221 FOR 83491 自定义排版
            // 派工
            // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
            $scope.settingList = [
                'op_no', 'op_name', 'wo_no', 'plot_no', 'qty', 'plot_start_time', 'plot_end_time', 'item_no', 'item_name', 'item_spec', 'mono_date', 'accessory_no',
                'item_version', 'BaseProcessNo', 'BaseProcessVersion', 'BoxQty', 'CUSTOMERNO', 'CartonQty', 'ERPMoLineNo', 'FACTORYNO', 'GRAPHNO', 'HotLot', 'ITEMNO', 'LOTDescription', 'LOTPriority',
                'LOTSTDQty', 'LOTplanstartdate', 'MOPRIORITY', 'MOUNITNO', 'MOplanstartdate', 'MPQty', 'MoDescription', 'MoSource', 'MoUser_Defined01', 'MoUser_Defined02', 'MoUser_Defined03', 'MoUser_Defined04', 'MoUser_Defined05',
                'MoUser_Defined11', 'MoUser_Defined12', 'MoUser_Defined13', 'MoUser_Defined21', 'MoUser_Defined22', 'MoUser_Defined23', 'PRODUCTTYPE', 'PalletQty', 'PrdDescription', 'PrdUser_Defined01',
                'PrdUser_Defined02', 'PrdUser_Defined03', 'PrdUser_Defined04', 'PrdUser_Defined05', 'PrdUser_Defined11', 'PrdUser_Defined12', 'PrdUser_Defined13', 'PrdUser_Defined21', 'PrdUser_Defined22',
                'PrdUser_Defined23', 'PriceType', 'ProductCode', 'ProductPCSNo', 'QCCategory', 'RONO', 'SerialTypeNo_COMP', 'SerialTypeNo_LOT', 'SpecNo', 'StockInLotNo', 'Storage_Spaces_No', 'Warehouse_No'
            ];
            // 已派工
            // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
            $scope.dispatchedSettingList = [
                'op_no', 'op_name', 'wo_no', 'plot_no', 'plot_qty', 'uncheck_in_qty', 'plot_start_time', 'plot_end_time', 'dis_start_time', 'disp_end_time', 'item_no', 'item_name', 'batch_mark', 'item_spec', 'tc_rate', 'tc_rate_for_all', 'c_rate_for_all', 'mono_date',
                'MOplanstartdate', 'CUSTOMERNO', 'RONO', 'ITEMNO', 'MOPRIORITY', 'MOUNITNO', 'MoDescription', 'MoSource', 'FACTORYNO', 'StockInLotNo', 'Warehouse_No', 'Storage_Spaces_No', 'ERPMoLineNo',
                'MoUser_Defined01', 'MoUser_Defined02', 'MoUser_Defined03', 'MoUser_Defined04', 'MoUser_Defined05', 'MoUser_Defined11', 'MoUser_Defined12', 'MoUser_Defined13', 'MoUser_Defined21', 'MoUser_Defined22', 'MoUser_Defined23',
                'PRODUCTTYPE', 'SpecNo', 'GRAPHNO', 'PrdDescription', 'CartonQty', 'PalletQty', 'BoxQty', 'ProductCode', 'SerialTypeNo_LOT', 'SerialTypeNo_COMP', 'LOTSTDQty', 'PrdUser_Defined01', 'PrdUser_Defined02', 'PrdUser_Defined03',
                'PrdUser_Defined04', 'PrdUser_Defined05', 'PrdUser_Defined11', 'PrdUser_Defined12', 'PrdUser_Defined13', 'PrdUser_Defined21', 'PrdUser_Defined22', 'PrdUser_Defined23', 'QCCategory', 'ProductPCSNo', 'MPQty', 'LOTPriority',
                'HotLot', 'LOTDescription', 'LOTplanstartdate', 'PriceType', 'BaseProcessNo', 'BaseProcessVersion'
            ];
            $scope.packList = [];
            $scope.moreInfoList = [];
            $scope.showTipsFlag = false;
            $scope.tempRow = {};
            $scope.tempDispatchRow = {};

            $scope.dispatchedPackList = [];
            $scope.dispatchedMoreInfoList = [];
            $scope.dispatchedShowTipsFlag = false;
            $scope.dispatchedTempRow = {};

            // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
            $scope.show_flag = {
                op_no: false,
                op_name: false,
                wo_no: false,
                plot_no: false,
                qty: false,
                plot_start_time: false,
                plot_end_time: false,
                item_no: false,
                item_name: false,
                item_spec: false,
                mono_date: false,
                accessory_no: false,
                item_version: false,
                BaseProcessNo: false,
                BaseProcessVersion: false,
                BoxQty: false,
                CUSTOMERNO: false,
                CartonQty: false,
                ERPMoLineNo: false,
                FACTORYNO: false,
                GRAPHNO: false,
                HotLot: false,
                ITEMNO: false,
                LOTDescription: false,
                LOTPriority: false,
                LOTSTDQty: false,
                LOTplanstartdate: false,
                MOPRIORITY: false,
                MOUNITNO: false,
                MOplanstartdate: false,
                MPQty: false,
                MoDescription: false,
                MoSource: false,
                MoUser_Defined01: false,
                MoUser_Defined02: false,
                MoUser_Defined03: false,
                MoUser_Defined04: false,
                MoUser_Defined05: false,
                MoUser_Defined11: false,
                MoUser_Defined12: false,
                MoUser_Defined13: false,
                MoUser_Defined21: false,
                MoUser_Defined22: false,
                MoUser_Defined23: false,
                PRODUCTTYPE: false,
                PalletQty: false,
                PrdDescription: false,
                PrdUser_Defined01: false,
                PrdUser_Defined02: false,
                PrdUser_Defined03: false,
                PrdUser_Defined04: false,
                PrdUser_Defined05: false,
                PrdUser_Defined11: false,
                PrdUser_Defined12: false,
                PrdUser_Defined13: false,
                PrdUser_Defined21: false,
                PrdUser_Defined22: false,
                PrdUser_Defined23: false,
                PriceType: false,
                ProductCode: false,
                ProductPCSNo: false,
                QCCategory: false,
                RONO: false,
                SerialTypeNo_COMP: false,
                SerialTypeNo_LOT: false,
                SpecNo: false,
                StockInLotNo: false,
                Storage_Spaces_No: false,
                Warehouse_No: false
            };
            // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
            $scope.dispatched_show_flag = {
                op_no: false,
                op_name: false,
                wo_no: false,
                plot_no: false,
                plot_qty: false,
                uncheck_in_qty: false,
                plot_start_time: false,
                plot_end_time: false,
                dis_start_time: false,
                disp_end_time: false,
                item_no: false,
                item_name: false,
                batch_mark: false,
                item_spec: false,
                tc_rate: false,
                tc_rate_for_all: false,
                c_rate_for_all: false,
                mono_date: false,
                MOplanstartdate: false,
                CUSTOMERNO: false,
                RONO: false,
                ITEMNO: false,
                MOPRIORITY: false,
                MOUNITNO: false,
                MoDescription: false,
                MoSource: false,
                FACTORYNO: false,
                StockInLotNo: false,
                Warehouse_No: false,
                Storage_Spaces_No: false,
                ERPMoLineNo: false,
                MoUser_Defined01: false,
                MoUser_Defined02: false,
                MoUser_Defined03: false,
                MoUser_Defined04: false,
                MoUser_Defined05: false,
                MoUser_Defined11: false,
                MoUser_Defined12: false,
                MoUser_Defined13: false,
                MoUser_Defined21: false,
                MoUser_Defined22: false,
                MoUser_Defined23: false,
                PRODUCTTYPE: false,
                SpecNo: false,
                GRAPHNO: false,
                PrdDescription: false,
                CartonQty: false,
                PalletQty: false,
                BoxQty: false,
                ProductCode: false,
                SerialTypeNo_LOT: false,
                SerialTypeNo_COMP: false,
                LOTSTDQty: false,
                PrdUser_Defined01: false,
                PrdUser_Defined02: false,
                PrdUser_Defined03: false,
                PrdUser_Defined04: false,
                PrdUser_Defined05: false,
                PrdUser_Defined11: false,
                PrdUser_Defined12: false,
                PrdUser_Defined13: false,
                PrdUser_Defined21: false,
                PrdUser_Defined22: false,
                PrdUser_Defined23: false,
                QCCategory: false,
                ProductPCSNo: false,
                MPQty: false,
                LOTPriority: false,
                HotLot: false,
                LOTDescription: false,
                LOTplanstartdate: false,
                PriceType: false,
                BaseProcessNo: false,
                BaseProcessVersion: false
            };
            // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
            $scope.show_label = {
                op_no: '',
                op_name: '',
                wo_no: '',
                plot_no: '',
                qty: '',
                plot_start_time: '',
                plot_end_time: '',
                item_no: '',
                item_name: '',
                item_spec: '',
                mono_date: '',
                accessory_no: '',
                item_version: '',
                BaseProcessNo: '',
                BaseProcessVersion: '',
                BoxQty: '',
                CUSTOMERNO: '',
                CartonQty: '',
                ERPMoLineNo: '',
                FACTORYNO: '',
                GRAPHNO: '',
                HotLot: '',
                ITEMNO: '',
                LOTDescription: '',
                LOTPriority: '',
                LOTSTDQty: '',
                LOTplanstartdate: '',
                MOPRIORITY: '',
                MOUNITNO: '',
                MOplanstartdate: '',
                MPQty: '',
                MoDescription: '',
                MoSource: '',
                MoUser_Defined01: '',
                MoUser_Defined02: '',
                MoUser_Defined03: '',
                MoUser_Defined04: '',
                MoUser_Defined05: '',
                MoUser_Defined11: '',
                MoUser_Defined12: '',
                MoUser_Defined13: '',
                MoUser_Defined21: '',
                MoUser_Defined22: '',
                MoUser_Defined23: '',
                PRODUCTTYPE: '',
                PalletQty: '',
                PrdDescription: '',
                PrdUser_Defined01: '',
                PrdUser_Defined02: '',
                PrdUser_Defined03: '',
                PrdUser_Defined04: '',
                PrdUser_Defined05: '',
                PrdUser_Defined11: '',
                PrdUser_Defined12: '',
                PrdUser_Defined13: '',
                PrdUser_Defined21: '',
                PrdUser_Defined22: '',
                PrdUser_Defined23: '',
                PriceType: '',
                ProductCode: '',
                ProductPCSNo: '',
                QCCategory: '',
                RONO: '',
                SerialTypeNo_COMP: '',
                SerialTypeNo_LOT: '',
                SpecNo: '',
                StockInLotNo: '',
                Storage_Spaces_No: '',
                Warehouse_No: ''
            };
            // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
            $scope.dispatched_show_label = {
                op_no: '',
                op_name: '',
                wo_no: '',
                plot_no: '',
                plot_qty: '',
                uncheck_in_qty: '',
                plot_start_time: '',
                plot_end_time: '',
                dis_start_time: '',
                disp_end_time: '',
                item_no: '',
                item_name: '',
                batch_mark: '',
                item_spec: '',
                tc_rate: '',
                tc_rate_for_all: '',
                c_rate_for_all: '',
                mono_date: '',
                MOplanstartdate: '',
                CUSTOMERNO: '',
                RONO: '',
                ITEMNO: '',
                MOPRIORITY: '',
                MOUNITNO: '',
                MoDescription: '',
                MoSource: '',
                FACTORYNO: '',
                StockInLotNo: '',
                Warehouse_No: '',
                Storage_Spaces_No: '',
                ERPMoLineNo: '',
                MoUser_Defined01: '',
                MoUser_Defined02: '',
                MoUser_Defined03: '',
                MoUser_Defined04: '',
                MoUser_Defined05: '',
                MoUser_Defined11: '',
                MoUser_Defined12: '',
                MoUser_Defined13: '',
                MoUser_Defined21: '',
                MoUser_Defined22: '',
                MoUser_Defined23: '',
                PRODUCTTYPE: '',
                SpecNo: '',
                GRAPHNO: '',
                PrdDescription: '',
                CartonQty: '',
                PalletQty: '',
                BoxQty: '',
                ProductCode: '',
                SerialTypeNo_LOT: '',
                SerialTypeNo_COMP: '',
                LOTSTDQty: '',
                PrdUser_Defined01: '',
                PrdUser_Defined02: '',
                PrdUser_Defined03: '',
                PrdUser_Defined04: '',
                PrdUser_Defined05: '',
                PrdUser_Defined11: '',
                PrdUser_Defined12: '',
                PrdUser_Defined13: '',
                PrdUser_Defined21: '',
                PrdUser_Defined22: '',
                PrdUser_Defined23: '',
                QCCategory: '',
                ProductPCSNo: '',
                MPQty: '',
                LOTPriority: '',
                HotLot: '',
                LOTDescription: '',
                LOTplanstartdate: '',
                PriceType: '',
                BaseProcessNo: '',
                BaseProcessVersion: '',
            };
            if (localStorage.getItem('customLayout')) {
                var settingsList = JSON.parse(localStorage.getItem('customLayout'));
                var settingsIdx = settingsList.findIndex(function (item) {
                    return item.page_id == 'WIP007' && item.div_id == 'undsplist';
                });
                if (settingsIdx !== -1 && settingsList[settingsIdx].view_desc) {
                    let tempList = JSON.parse(settingsList[settingsIdx].view_desc).data;
                    tempList.forEach(t => {
                        $scope.packList.push(t.col[0]);
                    });
                    $scope.moreInfoList = JSON.parse(settingsList[settingsIdx].view_desc).list;
                }
                if ($scope.packList.length > 0) {
                    $scope.packList.forEach(p => {
                        let data = $scope.settingList.filter(l => p.fieldId == l);
                        if (data.length > 0){
                            $scope.show_flag[p.fieldId] = true;
                            $scope.show_label[p.fieldId] = p.fieldName;
                        }
                    });
                } else {
                    $scope.getInitData();
                }

                // 已派工
                var dispatchedSettingsIdx = settingsList.findIndex(function (item) {
                    return item.page_id == 'WIP007' && item.div_id == 'ondsplist';
                });
                if (dispatchedSettingsIdx !== -1 && settingsList[dispatchedSettingsIdx].view_desc) {
                    let tempList = JSON.parse(settingsList[dispatchedSettingsIdx].view_desc).data;
                    tempList.forEach(t => {
                        $scope.dispatchedPackList.push(t.col[0]);
                    });
                    $scope.dispatchedMoreInfoList = JSON.parse(settingsList[dispatchedSettingsIdx].view_desc).list;
                }
                if ($scope.dispatchedPackList.length > 0) {
                    $scope.dispatchedPackList.forEach(p => {
                        let data = $scope.dispatchedSettingList.filter(l => p.fieldId == l);
                        if (data.length > 0) {
                            $scope.dispatched_show_flag[p.fieldId] = true;
                            $scope.dispatched_show_label[p.fieldId] = p.fieldName;
                        }
                    });
                } else {
                    $scope.getDispatchedInitData();
                }
            } else {
                $scope.getInitData();
                $scope.getDispatchedInitData();
            }
            // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
            // step 1. 取得區域
            $scope.loadAreaInfo();
        };

        // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
        $scope.getInitData = function () {
            $scope.show_flag.op_no = true;
            $scope.show_flag.op_name = true;
            $scope.show_flag.wo_no = true;
            $scope.show_flag.plot_no = true;
            $scope.show_flag.qty = true;
            $scope.show_flag.plot_start_time = true;
            $scope.show_flag.plot_end_time = true;
            $scope.show_flag.item_no = true;
            $scope.show_flag.item_name = true;
            $scope.show_flag.item_spec = true;
            $scope.show_flag.mono_date = true;
            $scope.show_flag.accessory_no = true;
            $scope.show_label.op_no = $filter('translate')('A02.list.column1');
            $scope.show_label.op_name = $filter('translate')('A02.list.column2');
            $scope.show_label.wo_no = $filter('translate')('A02.list.column12');
            $scope.show_label.plot_no = $filter('translate')('A02.list.column3');
            $scope.show_label.qty = $filter('translate')('A02.list.column4');
            $scope.show_label.plot_start_time = $filter('translate')('A02.list.column7');
            $scope.show_label.plot_end_time = $filter('translate')('A02.list.column8');
            $scope.show_label.item_no = $filter('translate')('A02.list.column5');
            $scope.show_label.item_name = $filter('translate')('A02.list.column6');
            $scope.show_label.item_spec = $filter('translate')('A02.list.column13');
            $scope.show_label.mono_date = $filter('translate')('A02.list.column16');
            $scope.show_label.accessory_no = $filter('translate')('A02.list.column17');
        };

        // 20211217 modify by Alan for#104583 : 刪除last_date與next_date
        $scope.getDispatchedInitData = function () {
            $scope.dispatched_show_flag.op_no = true,
            $scope.dispatched_show_flag.op_name = true,
            $scope.dispatched_show_flag.wo_no = true,
            $scope.dispatched_show_flag.plot_no = true,
            $scope.dispatched_show_flag.plot_qty = true,
            $scope.dispatched_show_flag.uncheck_in_qty = true,
            $scope.dispatched_show_flag.plot_start_time = true,
            $scope.dispatched_show_flag.plot_end_time = true,
            $scope.dispatched_show_flag.dis_start_time = true,
            $scope.dispatched_show_flag.disp_end_time = true,
            $scope.dispatched_show_flag.item_no = true,
            $scope.dispatched_show_flag.item_name = true,
            $scope.dispatched_show_flag.batch_mark = true,
            $scope.dispatched_show_flag.item_spec = true,
            $scope.dispatched_show_flag.tc_rate = true,
            $scope.dispatched_show_flag.tc_rate_for_all = true,
            $scope.dispatched_show_flag.c_rate_for_all = true,
            $scope.dispatched_show_flag.mono_date = true,
            $scope.dispatched_show_label.op_no = $filter('translate')('customLayout.ondsplist.column0'),
            $scope.dispatched_show_label.op_name = $filter('translate')('customLayout.ondsplist.column1'),
            $scope.dispatched_show_label.wo_no = $filter('translate')('customLayout.ondsplist.column2'),
            $scope.dispatched_show_label.plot_no = $filter('translate')('customLayout.ondsplist.column3'),
            $scope.dispatched_show_label.plot_qty = $filter('translate')('customLayout.ondsplist.column4'),
            $scope.dispatched_show_label.uncheck_in_qty = $filter('translate')('customLayout.ondsplist.column5'),
            $scope.dispatched_show_label.plot_start_time = $filter('translate')('customLayout.ondsplist.column6'),
            $scope.dispatched_show_label.plot_end_time = $filter('translate')('customLayout.ondsplist.column7'),
            $scope.dispatched_show_label.dis_start_time = $filter('translate')('customLayout.ondsplist.column8'),
            $scope.dispatched_show_label.disp_end_time = $filter('translate')('customLayout.ondsplist.column9'),
            $scope.dispatched_show_label.item_no = $filter('translate')('customLayout.ondsplist.column10'),
            $scope.dispatched_show_label.item_name = $filter('translate')('customLayout.ondsplist.column11'),
            $scope.dispatched_show_label.batch_mark = $filter('translate')('customLayout.ondsplist.column12'),
            $scope.dispatched_show_label.item_spec = $filter('translate')('customLayout.ondsplist.column13'),
            $scope.dispatched_show_label.tc_rate = $filter('translate')('customLayout.ondsplist.column14'),
            $scope.dispatched_show_label.tc_rate_for_all = $filter('translate')('customLayout.ondsplist.column15'),
            $scope.dispatched_show_label.c_rate_for_all = $filter('translate')('customLayout.ondsplist.column16'),
            $scope.dispatched_show_label.mono_date = $filter('translate')('customLayout.ondsplist.column19')
        };

        // 显示派工Tips
        $scope.showTips = function (item, e, i) {
            $scope.tempRow = item;
            e.preventDefault();
            e.stopPropagation();
            $scope.showTipsFlag = true;
            var popovertip = angular.element(document.getElementById('popover_id'));
            var index = document.getElementById('item' + i);
            popovertip.css('display', 'block');
            popovertip.css('top', $(index).offset().top + 5 + 'px');
            popovertip.css('left', $(index).offset().left + 'px');

        }
        // 隐藏派工Tips
        $scope.hideTips = function (item, e) {
            e.preventDefault();
            e.stopPropagation();
            $scope.showTipsFlag = false;
            $scope.tempRow = {};
        }

        // 显示待排Tips
        $scope.showDispatchTips = function (item, e, i) {
            $scope.dispatchedTempRow = item;
            e.preventDefault();
            e.stopPropagation();
            $scope.dispatchedShowTipsFlag = true;
            var popovertip = angular.element(document.getElementById('popover_id_wait'));
            var index = document.getElementById('item' + i);
            popovertip.css('display', 'block');
            popovertip.css('top', $(index).offset().top + 30 + 'px');
            popovertip.css('left', $(index).offset().left + 20 + 'px');

        }
        // 隐藏待排Tips
        $scope.hideDispatchTips = function (item, e) {
            e.preventDefault();
            e.stopPropagation();
            $scope.dispatchedShowTipsFlag = false;
            $scope.dispatchedTempRow = {};
        }

        // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
        $scope.loadAreaInfo = function() {
            $MMWService.pageNumberInfoGet({
                page_mode : '54',
                query_condition_info: [
                    {column_name:'A.MASTERNO', query_mode:'0', value:config.cache.account, merge_condition_model:'AND'}
                ],
            }, function(itemList){
                if(itemList.length != 0){
                    $scope.area_detail = itemList;
                    $scope.selectareaNo = $scope.area_detail[0].page_no;
                    $scope.selectareaName = $scope.area_detail[0].page_no + ' (' + $scope.area_detail[0].page_name + ')';
                    $scope.isLine = $scope.area_detail[0].area_type||'0';
                    $scope.selectWorkStation = '';
                    $scope.selectWorkStationName = '';
                    //step 2. 把第一筆區域當成預設值並帶入search 內查詢出資訊
                    search({return_type:'111'});
                } else {
                    $scope.$root.showAlert($filter('translate')('A02.msg.noArea1'));
                }
    
            });
        }

        // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
        $scope.loadMyFavorites = function() {
            $MMWService.showQueryListPNIG({
                page_mode: 53,
                mode:'M',
                key:'page_no',
                header : [
                    {label: $filter('translate')('common.queryList.area_c'), code:'page_no'},
                    {label: $filter('translate')('common.queryList.area_n'), code:'page_name'}
                ],
                selectKey:{key:'isselect', true: '1', false: '0'},
                setCondition:function(conditions){
                    conditions.push({column_name:'MASTERNO', query_mode:'0', value:config.cache.account, merge_condition_model:'AND' });
                    return conditions;
                },
                confirm: function(selectItem, dialog){
                    // 向数据库插入我的最爱数据信息
                    var content = {
                        master_no: config.cache.account, // 用户编号
                        master_type: 7,
                        favourite_user_area:[]
                    };
                    selectItem.forEach(function(item){
                        if(item.isselect == '1'){
                            content.favourite_user_area.push({area_no:item.page_no});
                        }
                    });
                    if(content.favourite_user_area.length == 0){
                        $scope.$root.showAlert($filter('translate')('A02.msg.lessThan'));
                    }else{
                        $MMWService.sendToServer({
                            uri : 'ServicesSTD.Module_SYS.favourite_machine_process',
                            content : content,
                            success : function(data){
                                dialog.hide();
                                $scope.loadAreaInfo();
                            }
                        });
                    }
                }
            });
        };
        // 加载自定义排版
        $scope.loadSysSettings = function () {
            var resultList = [];
            resultList.push({ code: 'undsplist', label: $filter('translate')('customLayout.undsplistName') });
            resultList.push({ code: 'ondsplist', label: $filter('translate')('customLayout.ondsplistName') });
            $scope.showSelect({
                title: $filter('translate')('common.msg.plz_select'),
                label: 'label',
                code: 'code',
                list: resultList,
                confirm: function (item, d) {
                    d.hide();
                    let tempList = {};
                    var divId = '';
                    if (item.code == 'undsplist') {
                        divId = 'undsplist';
                        $scope.settingList.forEach(l => {
                            tempList[l] = null;
                        });
                    } else {
                        divId = 'ondsplist';
                        $scope.dispatchedSettingList.forEach(l => {
                            tempList[l] = null;
                        });
                    }
                    
                    $mdDialog.serviceDialog('customerLayoutService', {
                        pageId: 'WIP007',
                        divId: divId,
                        styleFlag: false, // 是否控制行数限制
                        moreFlag: true,   // 是否显示更多排版页签
                        list: tempList,
                        callback: function () {
                            $state.reload();
                        }
                    });

                }
            });
        };

        $scope.back = function(){
            $scope.$root.hideMenu();
            $scope.$root.changeProgram('home', true);
        };
        $scope.orderbychange  = function(mode)
        {
            //console.log($scope.order_by_mode);
            if($scope.order_by_mode.name != mode)
            {
                $scope.order_by_mode.name = mode;
                $scope.order_by_mode.sort = false;
            }
            else
            {
                if($scope.order_by_mode.sort)
                    $scope.order_by_mode.sort = false;
                else
                    $scope.order_by_mode.sort = true;
            }
           
        }
        function search(content, feedback){

            // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
            if($scope.area_detail.length == 0){
                var msg = $filter('translate')('A02.alert.msg2');
                $scope.$root.showConfirm(msg, function(dialog)
                {
                   dialog.hide();
                   $scope.loadMyFavorites();
                   
                });
                return;
            }

            //未派工
            content.dispatch_detail_condition = [{
                wo_no : $scope.unassigned_wo_no||'',
                plot_no : $scope.unassigned_plot_no||''
            }];
            //已派工
            content.machine_detail_condition = [{
                wo_no : $scope.assigned_wo_no||'',
                plot_no : $scope.assigned_plot_no||''
            }];
            //當有設定已派工查詢條件時，不可變更已派工順序
            if(content.machine_detail_condition[0].wo_no == '' && content.machine_detail_condition[0].plot_no == ''){
                $scope.is_lock_sort = false;
            } else {
                $scope.is_lock_sort = true;
            }
            content.op_no = '';
            content.area_no = $scope.selectareaNo;
            content.work_date = moment($scope.work_date).format('YYYY-MM-DD');

            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_WIP.dispatch_area_info_get',
                content : content,
                success : function(data){
                    var errorMsg = '';
                    //產品資料
                    if(data.product_detail && data.product_detail.length > 0)
                        $scope.product_detail = data.product_detail;
                    //未派工
                    if(content.return_type.charAt(0) == '1'){
                        $scope.dispatch_detail = data.dispatch_detail;
                        if($scope.dispatch_detail.length == 0){
                            if(content.dispatch_detail_condition[0].wo_no == ''
                                && content.dispatch_detail_condition[0].plot_no == ''){
                                errorMsg += $filter('translate')('A02.msg.B0201first')+'<br>';
                            } else {
                                errorMsg += $filter('translate')('common.msg.no_data')+'<br>';
                            }
                        }
                    }

                    //已派工
                    if(content.return_type.charAt(1) == '1'){

                        // 20200319 modify by WeiTing for M#62127 - 增加過濾已派工的設備編號或設備名稱。
                        if($scope.assigned_machine == ''){
                            $scope.machine_detail = data.machine_detail;
                        } else {
                            var machine_detail_filter = [];
                            data.machine_detail.forEach(function(item){
                                if(item.machine_no.indexOf($scope.assigned_machine) != -1 
                                || item.machine_name.indexOf($scope.assigned_machine) != -1){
                                    machine_detail_filter.push(item);
                                } 
                            });
                            $scope.machine_detail = machine_detail_filter;
                        };

                        if($scope.machine_detail.length == 0){
                            if(content.machine_detail_condition[0].wo_no == ''
                                && content.machine_detail_condition[0].plot_no == ''){
                                errorMsg += $filter('translate')('A02.msg.A01first')+'<br>';
                            } else {
                                errorMsg += $filter('translate')('common.msg.no_data')+'<br>';
                            }
                            $scope.pageInfo.totlePage = 1;
                        } else {
                            //算出機台總筆數
                            $scope.pageInfo.totlePage = Math.ceil($scope.machine_detail.length/$scope.pageInfo.perPageRow);
                        }
                    }

                    if(content.return_type.charAt(2) == '1'){
                        //M#95547 熱處理優化 爐量顯示
                        var op_has_ht = 0;  // 熱處理 作業站計數
                        $scope.selectWorkStationName = '';
                        $scope.op_group_detail = data.op_group_detail;
                        if($scope.op_group_detail && $scope.op_group_detail.length>0){
                            //M#95547 熱處理優化 爐量顯示
                            var op_has_ht = 0;  // 熱處理 作業站計數
                            $scope.op_group_detail.forEach(function(item){
                                if(item.is_select == 'true')
                                    $scope.selectWorkStationName += item.op_name + ' \\ ';
                                if(item.plugin == 1) // plugin == 1 == 熱處理 作業站
                                    op_has_ht++;
                            });
                             //判斷是否有熱處理作業站  大於 0 顯示爐量 
                            if(op_has_ht > 0)
                                $scope.ht_tr_bool = true;
                            else
                                $scope.ht_tr_bool = false;
                            $scope.selectWorkStationName = $scope.selectWorkStationName.substr(0, $scope.selectWorkStationName.length-3);
                        }
                    }

                    if(errorMsg!=''){
                        $scope.$root.showAlert(errorMsg);
                    }

                    if(feedback)
                        feedback();
                    
                    EquipmentSortAction();
                }
            });
        }

        //未派工查詢
        $scope.unassigned_search = function(){
            search({return_type:'100'});
        };

        //清除未派工查詢
        $scope.unassigned_clear = function(){
            $scope.unassigned_wo_no = '';
            $scope.unassigned_plot_no = '';
            search({return_type:'100'});
        };

        //已派工查詢
        $scope.assigned_search = function(){
            if($scope.Mode == 'MachineExpend'){
                initMachineExpend($scope.selectMachine);
            } else {
                search({return_type:'010'});
            }
        };

        //清除已派工查詢
        $scope.assigned_clear = function(){
            $scope.assigned_wo_no = '';
            $scope.assigned_plot_no = '';
            $scope.assigned_search();
        };
        dis_date_separate_action = function()
        {
            if($scope.dispatched_detail && $scope.dispatched_detail.length > 0)
            {
                $scope.dispatched_detail.forEach(function(item){
                    if(item.dis_plot_start_time && item.dis_plot_start_time != "")
                    {
                        var str_list = item.dis_plot_start_time.split(" ");
                        if(str_list.length >= 2)
                        {
                            item.dis_start_date = str_list[0];
                            item.dis_start_time = str_list[1];
                        }
                    }
                    else
                    {
                        item.dis_start_date = moment($scope.work_date).format('YYYY-MM-DD');
                        item.dis_start_time = "00:00:00";
                    }
                    if(item.disp_plot_end_time && item.disp_plot_end_time != "")
                    {
                        var str_list = item.disp_plot_end_time.split(" ");
                        if(str_list.length >= 2)
                        {
                            item.disp_end_date = str_list[0];
                            item.disp_end_time = str_list[1];
                        }
                    }
                    else
                    {
                        item.disp_end_date = moment($scope.work_date).format('YYYY-MM-DD');
                        item.disp_end_time = "00:00:00";
                    }
                });
            }
        }
        $scope.time_open_set = function(event,detail,time,type)
        {
            var target = event.currentTarget;
            angular.element(target).addClass('is-focus');
            var rule = /^\d{2}:\d{2}:\d{2}$/;
            if(rule.test(time) == false)
                time = "00:00:00";
            $calculater.open(function(timeDisplay,dialog)
            { 
        	    angular.element(target).removeClass('is-focus');
                var hour = timeDisplay.hour, min = timeDisplay.minute, sec = timeDisplay.second;
               
                var time_str = hour+":"+min+":"+sec;
                if((0 <= (+hour) && (+hour) < 24) && 
                (0 <= (+min) && (+min) < 60) && 
                (0 <= (+sec) && (+sec) < 60) && rule.test(time_str))
                {
                    var content = {};
                    var time_check = true;
                    content.need_dispatch_plot_detail = [];
                    if(type == 4)
                    {
                        detail.dis_start_time = time_str;
                        detail.dis_time = detail.dis_start_date+" "+time_str;
                        content.work_mode = "4";
                    }
                    else if(type == 5)
                    {
                        detail.dis_time = detail.disp_end_date+" "+time_str;
                        content.work_mode = "5";
                        if(Date.parse(detail.dis_plot_start_time) > Date.parse(detail.dis_time))
                            time_check = false;
                        if(time_check)
                            detail.disp_end_time = time_str; 
                    }
                    if(time_check)
                    {
                        content.need_dispatch_plot_detail.push({
                            plot_no:detail.plot_no,
                            op_no:detail.op_no,
                            qty:detail.plot_qty,
                            mo_no:detail.mo_no,
                            machine_no:$scope.selectMachine.machine_no,
                            plot_start_time:detail.plot_start_time,
                            plot_end_time:detail.plot_end_time,
                            dis_time:detail.dis_time
                        });
                        content.dispatch_to = [];
                        content.with_draw_mode = "0";
                        content.dispatch_day = moment($scope.work_date).format('YYYY-MM-DD');
                        $MMWService.sendToServer({
                            uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                            content :content,
                            success : function(data){
                                    search({return_type:'110'}, function(){
                                        $scope.$root.showToast($filter('translate')('A05.js.success'));
                                        $scope.Mode = 'MachineExpend';
                                        var machine = $filter('filter')($scope.machine_detail, {machine_no:$scope.selectMachine.machine_no});
                                        if(machine!=undefined && machine.length > 0)
                                        {
                                            $scope.selectMachine = machine[0];
                                        }
                                        initMachineExpend($scope.selectMachine);
                                    });
                            }
                        });
                    }
                    else
                        $scope.$root.showAlert($filter('translate')('A02.alert.time_error_msg'));
                    //console.log(content);
                    
                    angular.element(target).removeClass('is-focus');
                    dialog.hide();
                } else 
                {
                    if($scope.$root.showAlert)
                        $scope.$root.showAlert($filter('translate')('common.msg.time_format_error'));
                }
            },
            function(dialog){
    		    angular.element(target).removeClass('is-focus');
    		    dialog.hide();
    	    },
    	    {
                type:"date",
                defaultNum : time,
                title:$filter('translate')('common.msg.select_time'),
    		    decimal : false
    	    });
        };
        //選擇區域
        $scope.loadAreaList = function(){

            // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
            if($scope.area_detail.length == 0){
                var msg = $filter('translate')('A02.alert.msg2');
                $scope.$root.showConfirm(msg, function(dialog)
                {
                   dialog.hide();
                   $scope.loadMyFavorites();
                   
                });
                return;
            }

            $scope.$root.showQueryList({
                key:'page_no',
                header : [
                    {label: $filter('translate')('common.queryList.area_c'), code:'page_no'},
                    {label: $filter('translate')('common.queryList.area_n'), code:'page_name'}
                ],
                query: function(conditions, feedback){
                    feedback($scope.area_detail);
                },
                selectCode:$scope.selectareaNo||'',
                confirm: function(selectItem, dialog){
                    $scope.selectareaNo = selectItem.page_no;
                    $scope.selectareaName = selectItem.page_no + ' (' + selectItem.page_name + ')';
                    $scope.isLine = selectItem.area_type||'0';
                    dialog.hide();
                    //查出全部資料
                    search({return_type:'111'});
                }
            });
        };

        //選擇作業站
        $scope.loadWorkStationList = function(){
            var content = {};
            content.area_no = $scope.selectareaNo;
            content.return_type = "001";
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_WIP.dispatch_area_info_get',
                content : content,
                success : function(data){
                    if(data && data.op_group_detail)
                    {
                        $scope.op_group_detail = data.op_group_detail
                    }
                    $scope.$root.showQueryList({
                        mode:'M',
                        key:'op_no',
                        header : [
                            {label: $filter('translate')('common.queryList.op_c'), code:'op_no'},
                            {label: $filter('translate')('common.queryList.op_n'), code:'op_name'}
                        ],
                        query: function(conditions, feedback){
                            feedback($scope.op_group_detail);
                        },
                        selectKey:{key:'is_select', true:'true', false:'false'},
                        confirm: function(selectItem, dialog){
                            // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
                            var content = {
                                master_no: $scope.selectareaNo,
                                master_type: 8,
                                favourite_user_opno:[],
                                user_no: config.cache.account // 用户编号
                            },
                            selectWorkStationName = '';
                            selectItem.forEach(function(item){
                                if(item.is_select == 'true'){
                                    // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
                                    content.favourite_user_opno.push({op_no:item.op_no});
        
                                    selectWorkStationName += item.op_name + ' \\ ';
                                }
                            });
                            selectWorkStationName = selectWorkStationName.substr(-3, 3);
        
                            $MMWService.sendToServer({
                                uri : 'ServicesSTD.Module_SYS.favourite_machine_process',
                                content : content,
                                success : function(data){
                                    $scope.selectWorkStation = '';
                                    $scope.selectWorkStationName = selectWorkStationName;
                                    dialog.hide();
                                    search({return_type:'111'});
                                }
                            });
                        }
                    });
                }
            });
        };

        $scope.changeDate = function(){
            $datePicker.open($scope.work_date,
            function(dialog){
                $scope.work_date = dialog.datePacker.pickDate;
                dialog.hide();
                search({return_type:'010'}, function(){
                    if($scope.Mode == 'MachineExpend'){
                        initMachineExpend($scope.selectMachine);
                    }
                });
            },
            function(dialog){
                dialog.hide();
            },{});
        };

        $scope.prevDate = function(){
            $scope.work_date = moment($scope.work_date).add(-1,'d').toDate();
            search({return_type:'010'}, function(){
                if($scope.Mode == 'MachineExpend'){
                    initMachineExpend($scope.selectMachine);
                }
            });
        };

        $scope.nextDate = function(){
            $scope.work_date = moment($scope.work_date).add(1, 'd').toDate();
            search({return_type:'010'}, function(){
                if($scope.Mode == 'MachineExpend'){
                    initMachineExpend($scope.selectMachine);
                }
            });
        };

        var selectWorkItemCount = 0;
        $scope.itemSelect = function(index, work){
            if(work.status == '0'){
                // 此任務在智派工納入派工，不可重複勾選！
                return $scope.$root.showAlert($filter('translate')('A02.msg.sjds_dispatch_can_not_select')); 
            }
            if(work.checked == 'Y'){
                work.checked = undefined;
                selectWorkItemCount--;
            }else if(!work.checked){
                work.checked = 'Y';
                selectWorkItemCount++;
            }

            // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
            if(selectWorkItemCount==0){
                $scope.Mode = '';
                $scope.showMode = 'query';
            } else {
                $scope.Mode = 'EditSendWork';
                $scope.showMode = 'preview'
            }

            EquipmentSortAction();
        };
        $scope.itemAllAction = function()
        {
            if($scope.dispatch_detail.length <= 0)
                return;
            for(var i in $scope.dispatch_detail)
            {
                if($scope.select_all_bool)
                    $scope.dispatch_detail[i].checked = '';
                else
                {
                    // 狀態 0 代表任務在智派工納入派工，不可勾選！
                    if($scope.dispatch_detail[i].status == '0')
                        $scope.dispatch_detail[i].checked = '';
                    else
                        $scope.dispatch_detail[i].checked = 'Y';
                }
            }

            // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
            if($scope.select_all_bool)
            {
                $scope.showMode = "query"
                $scope.select_all_bool = false;  
                $scope.Mode = '';
                selectWorkItemCount = 0;
            }
            else
            {
                $scope.showMode = "preview"
                $scope.select_all_bool = true;     
                $scope.Mode = 'EditSendWork';
                selectWorkItemCount = $scope.dispatch_detail.length;
            }
        };

        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        var pdf_url;
        $scope.preview = function(){
            var plot_detail = [];
            if($scope.Mode == 'Rollback'){
                $scope.dispatched_detail.forEach(function(item){
                    if(item.checked == 'Y')
                    {
                        var info = {
                            plot_no: item.plot_no,
                            plot_qty: item.qty
                        }
                        plot_detail.push(info);
                    }
                });
            }else{
                var dispach_detail = $filter('filter')($scope.dispatch_detail,$scope.dispatch_filter);
                dispach_detail.forEach(function(detail, index){
                    if(detail.checked == 'Y'){
                        var info = {
                            plot_no: detail.plot_no,
                            plot_qty: detail.qty
                        }
                        plot_detail.push(info);
                    }
                });
            }

            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.runcard_pdf_get',
                content : {
                    course:($scope.show_history?'1':'0'),
                    plot_detail : plot_detail
                },
                success : function(data){

                    for(var i = 0; i < plot_detail.length; i++){
                        $scope.printList.push({
                            printNo: plot_detail[i].plot_no,
                            printType: '1' // 1: 流程卡打印 + 生產批開立; 3: 條碼標籤打印(補印); 4: 外包單 - 出貨打印; 5. 叫修作業;
                        });
                    }

                    pdf_url = data.runcard_pdf_get[0].url_pdf;
                    if(pdf_url.indexOf('http://') == -1){
                        pdf_url = 'http://'+config.server.ip+':'+config.server.port+ pdf_url;
                    }
                    if(config.setting.outsidePDF == 'Y'){
                        var fs = window.nodeRequire('fs'), RuncardPath;
                        try{
                            RuncardPath = window.nodeRequire('electron').remote.app.getAppPath();
                        }catch(e){
                            RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                        }
                        RuncardPath += '\\www\\Runcard';
                        if(!fs.existsSync(RuncardPath)){
                            fs.mkdirSync(RuncardPath);
                        }
                        $scope.$root.downloadFile(pdf_url, RuncardPath+'\\RuncardPreview.pdf', function(dist_path){
                            window.nodeRequire('electron').shell.openItem(dist_path);
                        });
                    } else {
                        showPDFViewer(pdf_url);
                    }
                }
            });
        };

        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        function showPDFViewer(pdf_url){
            try{
                window.nodeRequire('nw.gui').Window.open(pdf_url, {
                    title:'PDF Viewer',
                    show: false,
                    icon:'icon/icon.png',
                    focus:true
                }, function(win) {
                    win.on('loaded', function(){
                        win.show();
                        win.print();
                    });
                });
            } catch (e){
                $scope.showMode = 'print';
                document.getElementById('kmi-pdf-panel').src = 'JSplugins/pdfjs/web/viewer.html?file='+pdf_url+'&openfile=false&viewbookmark=false&printfile=false&download=false#zoom=page-width';
            }
        }

        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        $scope.print = function(){
            if(window.nodeRequire){
                var sumatraPDF = window.nodeRequire('sumatra-pdf');
                if(sumatraPDF){
                    var fs = window.nodeRequire('fs'), RuncardPath;
                    try{
                        RuncardPath = window.nodeRequire('electron').remote.app.getAppPath();
                    }catch(e){
                        RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                    }
                    RuncardPath += '\\www\\Runcard';
                    if(!fs.existsSync(RuncardPath)){
                        fs.mkdirSync(RuncardPath);
                    }
                    $scope.$root.downloadFile(pdf_url, RuncardPath+'\\RuncardPreview.pdf', function(dist_path){
                        $scope.$root.showLoading();
                        window.nodeRequire('sumatra-pdf').printWithSettings({
                            path:RuncardPath+'\\RuncardPreview.pdf',
                            success:function(){
                                printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                $scope.$root.hideLoading();
                                $scope.$root.showToast($filter('translate')('common.msg.success'));
                            },
                            error:function(error){
                                // 20201104 modify by WeiTing for M#77013 - 不清楚為何在實際列印後，有列印成一張紙或輸出成 PDF檔案時，都會執行 error區域，所以目前 error區域也先當列印完成後，把列印詳情回送給後台做記錄。
                                printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                $scope.$root.hideLoading();
                                $scope.$root.showToast($filter('translate')('common.msg.success'));
                                //console.error(error);
                            }
                        });
                    });
                } else {
                    window.frames['kmi-pdf-panel'].pdf_print();
                }
            } else {
                window.frames['kmi-pdf-panel'].pdf_print();
            }
            /*
            if(config.setting.printSetting){
                $PrintSetting.init({
                    callback:function(settings){
                        window.frames['kmi-pdf-panel'].pdf_print(settings);
                    }
                });
            } else {
                window.frames['kmi-pdf-panel'].pdf_print();
            }
            */
        };

        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        $scope.download = function(){
            window.frames['kmi-pdf-panel'].pdf_download();
        };

        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
        $scope.cancel = function(){
            if($scope.Mode == 'Rollback'){
                $scope.showMode = 'query';
            }else{
                $scope.showMode = 'preview';
            }
            document.getElementById('kmi-pdf-panel').src = '';
            $scope.printList = [];
        };

        // 20201216 ADD FOR M#83236-1
        // 列印完成後，需把列印詳情回送給後台做記錄
		function printWiplogProcess(){
			$MMWService.sendToServer({
				uri: 'ServicesSTD.Module_SN.print_wiplog_process',
				content : {
                    printList: $scope.printList
                },
				success : function(){
                    $scope.printList = [];
                }
			});
        }
        
        $scope.pageInfo = {
            nowPage : 1,
            totlePage : 1,
            perPage : 10,
            perPageRow: 5
        };

        $scope.machineStatus = function (status) {
            return 'status_' + status;
        };

        $scope.selectMachine = undefined;
        $scope.getMachineList = function(){
            var start = ($scope.pageInfo.nowPage - 1)*$scope.pageInfo.perPageRow;
            var end = ($scope.pageInfo.nowPage)*$scope.pageInfo.perPageRow;
            return $scope.machine_detail.slice(start,end);
        };

        $scope.prevPage = function(){
            if($scope.pageInfo.nowPage>1)
                $scope.pageInfo.nowPage--;
        };

        $scope.nextPage = function(){
            if($scope.pageInfo.nowPage < $scope.pageInfo.totlePage)
                $scope.pageInfo.nowPage++;
        };

        //展開機台上的已派工清單
        function expendMachine(index, item, event){
            
            if($scope.Mode != 'MachineExpend'){
                $scope.Mode = 'MachineExpend';
                $scope.selectMachine = item;
                $scope.selectMachine.dispatch_size = 0;
                initMachineExpend($scope.selectMachine);
            } else if(selectWorkItemCount!=0){
                $scope.Mode = 'EditSendWork';
                $scope.selectMachine = undefined;
            }
            event.preventDefault();
        }

        var sortablList, dispatched_detail_backup;
        function initMachineExpend(item){
            // 20201209 modify by 外包 for M#83152: 派工作业我的最爱设定
            if($scope.area_detail.length == 0){
                var msg = $filter('translate')('A02.alert.msg2');
                $scope.$root.showConfirm(msg, function(dialog)
                {
                   dialog.hide();
                   $scope.loadMyFavorites();
                   
                });
                return;
            }

            var content = {
                area_no: $scope.selectareaNo,
                machine_no: item.machine_no,
                work_date: moment($scope.work_date).format('YYYY-MM-DD'),
                machine_detail_condition : [{
                    wo_no : $scope.assigned_wo_no||'',
                    plot_no : $scope.assigned_plot_no||''
                }],
                return_type: '020'//已派工 20220314 modi by wangyq for M#107976 old:121
            };
            dispatch_info_get_machine_detail(content, function(dispatched_detail){
                if(sortablList){
                    sortablList.destroy();
                    sortablList = undefined;
                    dispatched_detail_backup = undefined;
                    $scope.dispatched_detail = [];
                }
                dispatched_detail_backup = dispatched_detail.slice();
                //20220929 modify by wangzy for 0119508: 华禹彩印：派工作业处部分已派工数据无法调整顺序
                var list = [];
                list = list.concat(dispatched_detail.filter(item => item.states != '0'));
                list = list.concat(dispatched_detail.filter(item => item.states == '0'));
                $scope.dispatched_detail = list;
                dis_date_separate_action();
                if(content.machine_detail_condition[0].wo_no == '' && content.machine_detail_condition[0].plot_no == ''){
                    $scope.is_lock_sort = false;
                } else {
                    $scope.is_lock_sort = true;
                }

                if(!$scope.is_lock_sort){
                    $timeout(function(){
                        sortablList = Sortable.create(document.getElementById('sortablelist'), {
                            ghostClass: 'ghost',
                            filter: '.undragable',
                            handle: '.sortable-btn',
                            onEnd: function (evt) {
                                if($scope.Mode != 'EditSeq')
                                    $scope.Mode = 'EditSeq';
                                //console.log(evt);
                                if(item.dispatch_size === undefined){
                                    item.dispatch_size = 0
                                }
                                var newIndex = evt.newIndex + item.dispatch_size;
                                var oldIndex = evt.oldIndex + item.dispatch_size;
                                var chooseItem = $scope.dispatched_detail.splice(oldIndex, 1)[0];
                                //20181218 add by Dustdusk for M#: 防止沒抓到還塞進陣列內
                                if(chooseItem != undefined){
                                    $scope.dispatched_detail.splice(newIndex, 0, chooseItem);
                                    $scope.$apply();
                                }
                            }
                        });
                    });
                } else {
                    $scope.$root.showToast($filter('translate')('A02.msg.cant_sort'));
                }
            });
        }

        var MachineListMode = '', dispatchItem, machineList;
        $scope.itemSendwork = function(index, item){
            if(item.status == '0'){
                // 此任務在智派工納入派工，不可重複勾選！
                return $scope.$root.showAlert($filter('translate')('A02.msg.sjds_dispatch_can_not_select'));
            }
            if($scope.Mode != 'EditSendWork'){
                var feedback = function(data){
                    MachineListMode = '1';//表示派工
                    dispatchItem = item;
                    machineList = EquipmentSortForDialogAction(item,data);
                    $mdDialog.dialog(
                            'module/moduleA/program/A02/A2_MachineList.tmp.html',
                            MachineListController
                    );
                };
                if($scope.isLine == '1')
                    getLineMachineList(item.plot_no, item.op_no, $scope.work_date, feedback);
                else
                    getMachineList($scope.work_date, feedback);
            }
        };

        $scope.itemAccessory = function (item) {
            $scope.acc_detail = [];
            if (!item.accessory_no) {
                $scope.$root.showAlert($filter('translate')('A02.msg.no_accessory_no'));
                return;
            }
            $scope.acc_detail = item.product_acc_detail;
            $mdDialog.dialog(
                'module/moduleA/program/A02/A2_AccList.tmp.html',
                AccDetailController
            );
        };

        function AccDetailController(dialog) {
            return {
                product_acc_detail: $scope.acc_detail,
                PageConfig: { page: 0, page_count: 25 },
                order_by_mode: {name:"",sort:false},
                dispatch_filter: {},
                orderbychange: function(mode)
                {
                    if(dialog.order_by_mode.name != mode)
                    {
                        dialog.order_by_mode.name = mode;
                        dialog.order_by_mode.sort = false;
                    }
                    else
                    {
                        if (dialog.order_by_mode.sort)
                            dialog.order_by_mode.sort = false;
                        else
                            dialog.order_by_mode.sort = true;
                    }
           
                },
                getPages: function (list,PageConfig, filterItem){
                    if (list) {
                        if (dialog.order_by_mode.name != "")
                            list = $filter('orderBy')(list, dialog.order_by_mode.name, dialog.order_by_mode.sort);
                        var temp_list = list.filter(function (item, index, array) {
                            var isOK = true,
                                keys = Object.keys(filterItem);
                            for (var i = 0; i < keys.length; i++) {
                                var key = keys[i];
                                if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                    if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                        isOK = false;
                                        break;
                                    }
                                }
                            }
                            return isOK;
                        });
                        if (PageConfig) {
                            if (temp_list.length != 0) {
                                PageConfig.total_page = Math.ceil(temp_list.length / PageConfig.page_count);

                                if (PageConfig.page >= PageConfig.total_page) {
                                    PageConfig.page = 0;
                                }
                                var index = PageConfig.page * PageConfig.page_count;
                                return temp_list.slice(index, index + PageConfig.page_count);
                            } else {
                                PageConfig.total_page = 1;
                                PageConfig.page = 0;
                            }
                        } else {
                            return temp_list;
                        }
                    } else {

                        return list;
                    }
                },
                back: function () {
                    dialog.hide();
                }
            }
        } 

        function MachineListController(dialog){
            return {
                isLine: $scope.isLine,
                MachineListMode:MachineListMode,
                work_date:$scope.work_date,
                dispatchItem: dispatchItem,
                machineList : machineList,
                mlightColor : $scope.mlightColor,
                order_by_mode: {name:"",sort:false},
                dispatch_filter: {},
                orderbychange: function(mode)
                {
                    if(dialog.order_by_mode.name != mode)
                    {
                        dialog.order_by_mode.name = mode;
                        dialog.order_by_mode.sort = false;
                    }
                    else
                    {
                        if (dialog.order_by_mode.sort)
                            dialog.order_by_mode.sort = false;
                        else
                            dialog.order_by_mode.sort = true;
                    }
           
                },
                getMachineList: function(list, filterItem){
                    if (list) {
                        if (dialog.order_by_mode.name != "")
                            list = $filter('orderBy')(list, dialog.order_by_mode.name, dialog.order_by_mode.sort);
                        var temp_list = list.filter(function (item, index, array) {
                            var isOK = true,
                                keys = Object.keys(filterItem);
                            for (var i = 0; i < keys.length; i++) {
                                var key = keys[i];
                                if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                    if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                        isOK = false;
                                        break;
                                    }
                                }
                            }
                            return isOK;
                        });
                        return temp_list;
                    } else {
                        return list;
                    }
                },
                changeDate:function(){
                    $datePicker.open(dialog.work_date,
                    function(mdDialog){
                        dialog.work_date = mdDialog.datePacker.pickDate;
                        mdDialog.hide();
                        var feedback = function(data){
                            dialog.machineList = data;
                        };
                        if($scope.isLine == '1')
                            getLineMachineList(dialog.dispatchItem.plot_no, dialog.dispatchItem.op_no, dialog.work_date, feedback);
                        else
                            getMachineList(dialog.work_date, feedback);
                    },
                    function(dialog){
                        dialog.hide();
                    },{});
                },
                prevDate:function(){
                    dialog.work_date = moment(dialog.work_date).add(-1,'d').toDate();
                    var feedback = function(data){
                        dialog.machineList = data;
                    };
                    if($scope.isLine == '1')
                        getLineMachineList(dialog.dispatchItem.plot_no, dialog.dispatchItem.op_no, dialog.work_date, feedback);
                    else
                        getMachineList(dialog.work_date, feedback);
                },
                nextDate:function(){
                    dialog.work_date = moment(dialog.work_date).add(1,'d').toDate();
                    var feedback = function(data){
                        dialog.machineList = data;
                    };
                    if($scope.isLine == '1')
                        getLineMachineList(dialog.dispatchItem.plot_no, dialog.dispatchItem.op_no, dialog.work_date, feedback);
                    else
                        getMachineList(dialog.work_date, feedback);
                },
                back : function(){
                    dialog.hide();
                },
                confirm : function(){
                    if(MachineListMode == '1'){
                        MachineListConfirmDispatch(dialog);
                    } else if(MachineListMode == '2'){
                        MachineListConfirmTransfer(dialog);
                    }
                    $scope.roll_back_all_bool = false;
                }
            };
        }

        function getMachineList(work_date, feedback){
            var content = {
                dispatch_detail_condition: [{wo_no : '', plot_no : ''}],//未派工
                machine_detail_condition: [{wo_no : '', plot_no : ''}],//已派工
                op_no: '',
                area_no: $scope.selectareaNo,
                work_date: moment(work_date).format('YYYY-MM-DD'),
                return_type:'010'
            };

            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_WIP.dispatch_area_info_get',
                content : content,
                success : function(data){
                    //已派工
                    if(data.machine_detail && data.machine_detail.length !=0){
                        if(feedback)
                            feedback(data.machine_detail);
                    } else {
                        $scope.$root.showAlert($filter('translate')('A02.msg.A01first'));
                    }
                }
            });
        }

        function getLineMachineList(plot_no, op_no, work_date, feedback){
            var content = {
                page_mode: 'dispatch_line_equipment_info_get',
                query_condition_info: []
            };
            content.query_condition_info.push({column_name: 'A.LOTNO', query_mode: '0', value: plot_no, merge_condition_model: 'AND'});
            content.query_condition_info.push({column_name: 'A.OPNO', query_mode: '0', value: op_no, merge_condition_model: 'AND'});
            content.query_condition_info.push({column_name: 'workdate', query_mode: '0', value: moment(work_date).format('YYYYMMDD')+'000000', merge_condition_model: 'AND'});

            $MMWService.pageNumberInfoGet(content, function(data){
                //已派工
                if(data && data.length !=0){
                    data.forEach(function(machine){
                        machine.used_capacity = Math.round(machine._used_capacity*100 / 60)/100;
                        machine.machine_load = Math.round(machine.used_capacity*100/machine.capacity);
                        if(machine.machine_load>80)
                            machine.load_status = 'H';
                        else if(machine.machine_load>=60)
                            machine.load_status = 'M';
                        else
                            machine.load_status = 'L';
                    });
                    if(feedback)
                        feedback(data);
                } else {
                    $scope.$root.showAlert($filter('translate')('A02.msg.A01first'));
                }
            });
        }

        //派工到多機台
        function MachineListConfirmDispatch(dialog){
            var dispatchSum = 0;
            var content = {
                need_dispatch_plot_detail:[dispatchItem],
                dispatch_to:[],
                work_mode:1,
                dispatch_day:moment(dialog.work_date).format('YYYY-MM-DD')
            };

            dialog.machineList.forEach(function(machine, index){
                if(machine.inputQty != undefined && machine.inputQty != 0){
                    content.dispatch_to.push({machine_no:machine.machine_no,qty: machine.inputQty});
                    dispatchSum+= (+machine.inputQty);
                }
            });
            
            var _fn = function(request){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                    content : request,
                    success : function(data){
                        if(data.dispatch_msg && data.dispatch_msg.length > 0)
                        {
                            var msg = data.dispatch_msg.join("<br>")
                            $scope.$root.showConfirm(msg, function(confirm_dialog){
                                confirm_dialog.hide();
                                enforce_dispatch_action(request,function(){
                                    dialog.hide();
                                    $scope.work_date = dialog.work_date;
                                    search({return_type:'110'}, function()
                                    {
                                        $scope.$root.showToast(dispatchItem.plot_no+ $filter('translate')('A02.msg.saveSuccess'));
                                    });
                                });
                            });
                        }
                        else
                        {
                            dialog.hide();
                            $scope.work_date = dialog.work_date;
                            search({return_type:'110'}, function()
                            {
                                $scope.$root.showToast(dispatchItem.plot_no+ $filter('translate')('A02.msg.saveSuccess'));
                            });
                        }
                    }
                });
            };

            if(content.dispatch_to.length == 0){
                //尚未輸入派工數量
                $scope.$root.showAlert($filter('translate')('A02.msg.no_dispatch_qty'));
            } else if(dispatchSum <= dispatchItem.qty){
                dispatch_info_calculation_process(content, function(data){
                    if(data &&  data.suggest_detail && data.suggest_detail.length > 0)
                    {
                        OpenMachineSuggestListDialog(1,content,data.suggest_detail);
                        dialog.hide();
                    }
                    else if(data && data.msg != '')
                    {
                        $scope.$root.showConfirm(data.msg, function(dialogType){
                            dialogType.hide();
                            _fn(content);
                        });
                    }
                    else
                    {
                        _fn(content);
                    };
                });
            } else {
                $scope.$root.showAlert($filter('translate')('A02.msg.numOver') + dispatchItem.qty);
            }
        }

        $scope.machineSelect = function(index, machine, event){
            if($scope.Mode == 'EditSendWork'){
                itemMutiSendwork(machine);
            } else {
                expendMachine(index, machine, event);
            }
        };

        $scope.closeMachine = function(){
            $scope.Mode = '';
            $scope.selectMachine = undefined;
            if(sortablList){
                sortablList.destroy();
                sortablList = undefined;
                dispatched_detail_backup = undefined;
                $scope.dispatched_detail = [];
            }
        };

        //多生產批同時派工
        function itemMutiSendwork(machine){
            var content = {
                need_dispatch_plot_detail:[],
                dispatch_to:[{machine_no : machine.machine_no,}],
                work_mode:1,
                dispatch_day:moment($scope.work_date).format('YYYY-MM-DD')
            };
            var filter_result = $filter('filter')($scope.dispatch_detail,$scope.dispatch_filter);
            filter_result.forEach(function(detail, index){
                if(detail.checked == 'Y'){
                    content.need_dispatch_plot_detail.push(detail);
                }
            });
            if(content.need_dispatch_plot_detail.length <= 0)
            {
                $scope.$root.showAlert($filter('translate')('A02.msg.no_dispatch_detail'));
                return ;
            }
            if(content.need_dispatch_plot_detail.length==1){
                content.dispatch_to[0].qty = content.need_dispatch_plot_detail[0].qty;
            }

            var _fn = function(request){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                    content : request,
                    success : function(data){
                        if(data.dispatch_msg && data.dispatch_msg.length > 0)
                        {
                            var msg = data.dispatch_msg.join("<br>")
                            $scope.$root.showConfirm(msg, function(confirm_dialog){
                                confirm_dialog.hide();
                                enforce_dispatch_action(request,function()
                                {
                                    search({return_type:'110'}, function(){
                                        $scope.$root.showToast(
                                            content.need_dispatch_plot_detail.length
                                            + $filter('translate')('A02.msg.sendWorkSuccess')
                                            + '['+machine.machine_no+']');
                                        $scope.Mode = '';
                                        selectWorkItemCount = 0;
                                        $scope.select_all_bool = false;
                                        // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
                                        $scope.showMode = 'query';
                                    });
                                });
                            });
                        }
                        else
                        {
                            search({return_type:'110'}, function(){
                                $scope.$root.showToast(
                                    content.need_dispatch_plot_detail.length
                                    + $filter('translate')('A02.msg.sendWorkSuccess')
                                    + '['+machine.machine_no+']');
                                $scope.Mode = '';
                                selectWorkItemCount = 0;
                                $scope.select_all_bool = false;
                                // 20201210 modify by 外包 for M#83236: 派工作业 - 增加流程卡列印
                                $scope.showMode = 'query';
                            });
                        }
                    }
                });
            };

            dispatch_info_calculation_process(content, function(data){
                if(data &&  data.suggest_detail &&  data.suggest_detail.length > 0)
                {
                    OpenMachineSuggestListDialog(0,content,data.suggest_detail);
                }
                else if(data && data.msg != '')
                {
                    $scope.$root.showConfirm(data.msg, function(dialogType){
                        dialogType.hide();
                        _fn(content);
                    });
                }
                else
                {
                    _fn(content);
                };
            });
        };
        //建議數量開窗 
        //work_mode = 0 =多筆生產批派一筆設備 
        //work_mode = 1 = 一筆生產批派多個設備
        //submit_data = 派工原始明細
        //suggest_detail = 派工建議明細
        function OpenMachineSuggestListDialog (work_mode,submit_data,suggest_detail)
        {
            $mdDialog.dialog(
                'module/moduleA/program/A02/A2_MachineList_suggest.html',
                function(dialog){
                    return {
                        suggest_detail:suggest_detail,
                        mlightColor : $scope.mlightColor,
                        submit_data:submit_data,
                        work_mode:work_mode,
                        order_by_mode: {name:"",sort:false},
                        dispatch_filter: {},
                        init :function()
                        {
                            
                        },
                        orderbychange: function(mode)
                        {
                            if(dialog.order_by_mode.name != mode)
                            {
                                dialog.order_by_mode.name = mode;
                                dialog.order_by_mode.sort = false;
                            }
                            else
                            {
                                if (dialog.order_by_mode.sort)
                                    dialog.order_by_mode.sort = false;
                                else
                                    dialog.order_by_mode.sort = true;
                            }
                
                        },
                        getSuggestDetail: function(list, filterItem){
                            if (list) {
                                if (dialog.order_by_mode.name != "")
                                    list = $filter('orderBy')(list, dialog.order_by_mode.name, dialog.order_by_mode.sort);
                                var temp_list = list.filter(function (item, index, array) {
                                    var isOK = true,
                                        keys = Object.keys(filterItem);
                                    for (var i = 0; i < keys.length; i++) {
                                        var key = keys[i];
                                        if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                                            if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                                isOK = false;
                                                break;
                                            }
                                        }
                                    }
                                    return isOK;
                                });
                                return temp_list;
                            } else {
                                return list;
                            }
                        },
                        checkSuggestQty: function(event,item)
                        {
                            var target = event.currentTarget;
                            angular.element(target).addClass('is-focus');
                            $calculater.open(
                                function(num,dialog)
                                { 
                                    angular.element(target).removeClass('is-focus');
                                    dialog.hide();
                                    if((+num) >= 0 && (+num) <= (+item.limit_qty))
                                        item.sug_qty = num;
                                    else
                                        $scope.$root.showAlert($filter('translate')('A02.suggest_list.alert2'));
                                },
                                //按下右上角X後會呼叫此function
                                function(dialog)
                                {
                                    angular.element(target).removeClass('is-focus');
                                    dialog.hide();
                                },
                                {
                                    defaultNum : item.sug_qty,
                                    decimal : false
                                });
                        },
                        back : function(){
                            dialog.hide();
                        },
                        submit_action:function(request)
                        {
                            $MMWService.sendToServer({
                                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                                content : request,
                                success : function(data){
                                    if(data.dispatch_msg && data.dispatch_msg.length > 0)
                                    {
                                        var msg = data.dispatch_msg.join("<br>")
                                        $scope.$root.showConfirm(msg, function(confirm_dialog){
                                            confirm_dialog.hide();
                                            enforce_dispatch_action(request,function()
                                            {
                                                search({return_type:'110'}, function(){
                                                    var str_array = [];
                                                    for(var i in request.dispatch_to)
                                                    {
                                                        var str = request.need_dispatch_plot_detail.length+
                                                        $filter('translate')('A02.msg.sendWorkSuccess')+'['+request.dispatch_to[i].machine_no+']'
                                                        str_array.push(str);
                                                    }
                                                    $scope.$root.showToast(str_array.join("<br>"));
                                                    $scope.Mode = '';
                                                    selectWorkItemCount = 0;
                                                    $scope.select_all_bool = false;
                                                    $scope.selectRollback = 0;
                                                    if($scope.selectMachine)
                                                        $scope.selectMachine.dispatch_size = 0;
                                                    //console.log($scope.selectMachine);
                                                    //$scope.selectMachine.dispatch_size = 0;
                                                });
                                            });
                                        });
                                    }
                                    else
                                    {
                                        search({return_type:'110'}, function(){
                                            var str_array = [];
                                            for(var i in request.dispatch_to)
                                            {
                                                var str = request.need_dispatch_plot_detail.length+
                                                $filter('translate')('A02.msg.sendWorkSuccess')+'['+request.dispatch_to[i].machine_no+']'
                                                str_array.push(str);
                                            }
                                            $scope.$root.showToast(str_array.join("<br>"));
                                            $scope.Mode = '';
                                            selectWorkItemCount = 0;
                                            $scope.select_all_bool = false;
                                            $scope.selectRollback = 0;
                                            if($scope.selectMachine)
                                                $scope.selectMachine.dispatch_size = 0;
                                            //console.log($scope.selectMachine);
                                            //$scope.selectMachine.dispatch_size = 0;
                                        });
                                    }
                                }
                            });
                        },
                        normal_confirm:function(){
                           
                            dialog.submit_action(dialog.submit_data);
                            dialog.hide();
                        },
                        suggest_confirm : function(){
                            var check_length = 0;
                            if(work_mode == 0)
                            {
                                for(var i in dialog.suggest_detail)  
                                {
                                    var op_no = dialog.suggest_detail[i].op_no;
                                    var lot_no = dialog.suggest_detail[i].lot_no;
                                    var sug_qty = dialog.suggest_detail[i].sug_qty;
                                    for(var j in dialog.submit_data.need_dispatch_plot_detail)
                                    {
                                        var org_op_no = dialog.submit_data.need_dispatch_plot_detail[j].op_no;
                                        var org_lot_no = dialog.submit_data.need_dispatch_plot_detail[j].plot_no;
                                        if(org_op_no == op_no &&  org_lot_no == lot_no)
                                                dialog.submit_data.need_dispatch_plot_detail[j].qty = sug_qty;
                                    }
                                }
                                dialog.submit_data.need_dispatch_plot_detail = 
                                dialog.submit_data.need_dispatch_plot_detail.filter(function(item){
                                    if(item.qty > 0)
                                        return item;
                                });
                                check_length = dialog.submit_data.need_dispatch_plot_detail.length;
                                if(dialog.submit_data.need_dispatch_plot_detail.length == 1)
                                {
                                    if(dialog.submit_data.dispatch_to && dialog.submit_data.dispatch_to.length  == 1)
                                    {
                                        dialog.submit_data.dispatch_to[0].qty = dialog.submit_data.need_dispatch_plot_detail[0].qty;
                                    }
                                }
                            }
                            else if(work_mode == 1)
                            {
                                for(var i in dialog.suggest_detail) 
                                {
                                    var equipment_no = dialog.suggest_detail[i].equipment_no;
                                    var sug_qty = dialog.suggest_detail[i].sug_qty;
                                    for(var j in dialog.submit_data.dispatch_to)
                                    {
                                        var org_equipment_no = dialog.submit_data.dispatch_to[j].machine_no;
                                        if(equipment_no == org_equipment_no)
                                            dialog.submit_data.dispatch_to[j].qty = sug_qty;
                                    }
                                }
                                dialog.submit_data.dispatch_to =
                                dialog.submit_data.dispatch_to.filter(function(item){
                                    if(item.qty > 0)
                                        return item;
                                });
                                check_length = dialog.submit_data.dispatch_to.length;
                            }
                            if(check_length > 0)
                                dialog.submit_action(dialog.submit_data);
                            else
                            {
                                search({return_type:'110'}, function(){
                                    $scope.$root.showAlert($filter('translate')('A02.suggest_list.alert1'));
                                    $scope.Mode = '';
                                    selectWorkItemCount = 0;
                                    $scope.select_all_bool = false;
                                    $scope.selectRollback = 0;
                                    if($scope.selectMachine)
                                        $scope.selectMachine.dispatch_size = 0;
                                });
                            }
                            dialog.hide();
                        }
                    }
                }
            );
        }
        $scope.mwlightColor = function(states){
            var lightColor;
            if(states == '0'){
                lightColor = 'light-white';
            } else if(states == '1'){
                lightColor = 'light-green';
            }if(states == '2'){
                lightColor = 'light-blue';
            }
            return lightColor;
        };

        $scope.mlightColor = function(states){
            var lightColor;
            if(states == 'H'){
                lightColor = 'red';
            } else if(states == 'M'){
                lightColor = 'yellow';
            }if(states == 'L'){
                lightColor = 'green';
            }
            return lightColor;
        };

        $scope.confirmEditSeq = function(){
            var content = {
                machine_no :$scope.selectMachine.machine_no,
                dispatch_plot_detail:[]
            };
            $scope.dispatched_detail.forEach(function(detail, index){
                content.dispatch_plot_detail.push({
                    plot_no:detail.plot_no,
                    op_no:detail.op_no,
                    seq:index
                });
                detail.seq = index;
            });
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.change_dispatch_seq_process',
                content : content,
                success : function(data){
                    $scope.$root.showToast($filter('translate')('A02.msg.seqChangeSuccess'));
                    $scope.Mode = 'MachineExpend';
                    //20221011 modify by wangzy for M#0120393: 华禹彩印：派工作业处--已派工数据调整顺序点击确定后在当前界面无法再操作调整
                    //确认调整顺序好要将dispatch_size值重置为0
                    $scope.selectMachine.dispatch_size = 0;
                    initMachineExpend($scope.selectMachine);
                }
            });
        };

        $scope.cancelEditSeq = function(){
            $scope.Mode = 'MachineExpend';
            $scope.dispatched_detail = dispatched_detail_backup.slice();
            dis_date_separate_action();
        };

        $scope.selectRollback = 0;
        $scope.detailRollback = function(index,detail){
            if(detail.status == '0'){
                // 此任務在智派工納入派工，不可重複勾選！
                return $scope.$root.showAlert($filter('translate')('A02.msg.sjds_dispatch_can_not_select'));
            }
            if($scope.Mode != 'EditSeq'){
                if(detail.checked == 'Y'){
                    detail.checked = undefined;
                    $scope.selectRollback--;
                }else if(!detail.checked){
                    detail.checked = 'Y';
                    $scope.selectRollback++;
                }
                if($scope.selectRollback==0){
                    $scope.Mode = 'MachineExpend';
                } else {
                    $scope.Mode = 'Rollback';
                }
            }
        };
        $scope.detailRollbackAll = function()
        {  
            if($scope.dispatched_detail.length <= 0)
                return;
            for(var i in $scope.dispatched_detail)
            {
                if($scope.roll_back_all_bool)
                    $scope.dispatched_detail[i].checked = '';
                else
                {
                    // 狀態 0 代表任務在智派工納入派工，不可勾選！
                    if($scope.dispatched_detail[i].status == '0')
                        $scope.dispatched_detail[i].checked = '';
                    else
                        $scope.dispatched_detail[i].checked = 'Y';
                }
            }
            if($scope.roll_back_all_bool)
            {
                $scope.roll_back_all_bool = false;
                $scope.selectRollback = 0;
                $scope.Mode = 'MachineExpend';
            }
            else
            {
                $scope.roll_back_all_bool = true;
                $scope.Mode = 'Rollback';
                $scope.selectRollback = $scope.dispatched_detail.length;
            }
        }
        //設備排序 select 開窗
        $scope.getEquipmentSortModeList = function()
        {
            $scope.$root.showSelect({
                label:"label",
                code: 'code',
                selectCode:$scope.equipment_sort_mode,
                list:$scope.equipment_sort_option_list,
                confirm: function (item,select_dialog) 
                {
                    select_dialog.hide();
                    if($scope.equipment_sort_mode != item.code)
                        $scope.equipment_sort_mode_change = true;
                    else
                        $scope.equipment_sort_mode_change = false;
                    $scope.equipment_sort_mode = item.code;
                    $scope.equipment_sort_mode_label = item.label;
                    EquipmentSortAction();
                }
            });
        }
        function EquipmentSortAction()
        {
            //模式改變 dis order score 歸零
            if($scope.equipment_sort_mode_change)
            {
                for(var i in $scope.machine_detail)
                    $scope.machine_detail[i].dis_order_score = 0
            }
            switch($scope.equipment_sort_mode)
            {
                // 20211125 modify by Alan for #0103170: [sMES]派工作業設備順序顛倒[宏毅]
                // 修正標準預設排序(case: 0,5,6,7)
                case "0":
                    $scope.machine_detail = $filter('orderBy')($scope.machine_detail,['machine_no']);
                    break;
                case "1":
                    $scope.machine_detail = $filter('orderBy')($scope.machine_detail,['times','machine_no'],true);
                    break;
                case "2":
                    $scope.machine_detail = $filter('orderBy')($scope.machine_detail,['good_rate','machine_no'],true);
                    break;
                case "3":
                    $scope.machine_detail = $filter('orderBy')($scope.machine_detail,['used_load','machine_no'],true);
                    break;
                case "4":
                    $scope.machine_detail = $filter('orderBy')($scope.machine_detail,['used_load','machine_no']);
                    break;
                case "5":
                    var dis_data = $filter('filter')($scope.dispatch_detail,{checked:"Y"});
                    var has_score = false;
                    dis_data.forEach(function(item)
                    {
                        var condition = {op_no:item.op_no,product_no:item.item_no,product_ver:item.item_version};
                        var equipment_data = $filter('filter')($scope.product_detail,condition);
                        equipment_data.forEach(function(eq_item){
                            $scope.machine_detail.forEach(function(m_item)
                            {
                                if(m_item.machine_no == eq_item.equipment_no)
                                    m_item.dis_order_score += eq_item.times;
                                
                                if(m_item.dis_order_score > 0)
                                    has_score = true;
                            });
                        });
                        
                    });
                    if($scope.Mode != "EditSendWork")
                        $scope.$root.showAlert($filter('translate')('A02.equipment_sort_list.alert_1'));  
                    $scope.machine_detail = has_score 
                        ? $filter('orderBy')($scope.machine_detail, ['dis_order_score', 'machine_no'], true)
                        : $filter('orderBy')($scope.machine_detail, ['machine_no']); 
                    break;
                case "6":
                    var dis_data = $filter('filter')($scope.dispatch_detail,{checked:"Y"});
                    var has_score = false;
                    dis_data.forEach(function(item)
                    {
                        var condition = {op_no:item.op_no,product_no:item.item_no,product_ver:item.item_version};
                        var equipment_data = $filter('filter')($scope.product_detail,condition);
                        equipment_data.forEach(function(eq_item){
                            $scope.machine_detail.forEach(function(m_item)
                            {
                                if(m_item.machine_no == eq_item.equipment_no)
                                    m_item.dis_order_score += eq_item.good_rate;
                                if(m_item.dis_order_score > 0)
                                    has_score = true;
                            });
                        });
                    });
                    if($scope.Mode != "EditSendWork")
                        $scope.$root.showAlert($filter('translate')('A02.equipment_sort_list.alert_1'));
                    $scope.machine_detail = has_score 
                        ? $filter('orderBy')($scope.machine_detail, ['dis_order_score', 'machine_no'], true)
                        : $filter('orderBy')($scope.machine_detail, ['machine_no']);
                    break;
                case "7":
                    var dis_data = $filter('filter')($scope.dispatch_detail,{checked:"Y"});
                    var has_score = false;
                    dis_data.forEach(function(item)
                    {
                        var condition = {op_no:item.op_no,product_no:item.item_no,product_ver:item.item_version};
                        var equipment_data = $filter('filter')($scope.product_detail,condition);
                        equipment_data.forEach(function(eq_item){
                            $scope.machine_detail.forEach(function(m_item)
                            {
                                if(m_item.machine_no == eq_item.equipment_no)
                                    m_item.dis_order_score += eq_item.equipment_seq;
                                if(m_item.dis_order_score > 0)
                                    has_score = true;
                            });
                        });
                    });
                    if($scope.Mode != "EditSendWork")
                        $scope.$root.showAlert($filter('translate')('A02.equipment_sort_list.alert_1'));
                    $scope.machine_detail = has_score 
                        ? $filter('orderBy')($scope.machine_detail, ['dis_order_score', 'machine_no'])
                        : $filter('orderBy')($scope.machine_detail, ['machine_no']);
                    break;
            }
            //console.log($scope.machine_detail);
        }
         //設備排序動作(改派 與 分量派)
        function EquipmentSortForDialogAction(dis_item,machine_data)
        {
             //init score for sort
             for(var i in machine_data)
                 machine_data[i].dis_order_score = 0
             //console.log(data);
             if(typeof dis_item === "undefined")
                 return;
             if(typeof machine_data === "undefined" || machine_data.length <= 0)
                 return;
 
             switch($scope.equipment_sort_mode)
             {
                // 20211125 modify by Alan for #0103170: [sMES]派工作業設備順序顛倒[宏毅]
                // 修正標準預設排序(case: 0,5,6,7)
                 case "0":
                     machine_data = $filter('orderBy')(machine_data,['machine_no']);
                     break;
                 case "1":
                     machine_data = $filter('orderBy')(machine_data,['times','machine_no'],true);
                     break;
                 case "2":
                     machine_data = $filter('orderBy')(machine_data,['good_rate','machine_no'],true);
                     break;
                 case "3":
                     machine_data = $filter('orderBy')(machine_data,['used_load','machine_no'],true);
                     break;
                 case "4":
                     machine_data = $filter('orderBy')(machine_data,['used_load','machine_no']);
                     break;
                 case "5":
                         var dis_data = [dis_item];
                         var has_score = false;
                         dis_data.forEach(function(item)
                         {
                             var condition = {op_no:item.op_no,product_no:item.item_no,product_ver:item.item_version};
                             var equipment_data = $filter('filter')($scope.product_detail,condition);
                             equipment_data.forEach(function(eq_item){
                                 machine_data.forEach(function(m_item)
                                 {
                                     if(m_item.machine_no == eq_item.equipment_no)
                                         m_item.dis_order_score += eq_item.times;
                                     
                                     if(m_item.dis_order_score > 0)
                                         has_score = true;
                                 });
                             });
                             
                         });
                         machine_data = has_score 
                             ? $filter('orderBy')(machine_data, ['dis_order_score', 'machine_no'], true)
                             : $filter('orderBy')(machine_data, ['machine_no']);       
                     break;
                 case "6":
                     var dis_data = [dis_item];
                     var has_score = false;
                     dis_data.forEach(function(item)
                     {
                             var condition = {op_no:item.op_no,product_no:item.item_no,product_ver:item.item_version};
                             var equipment_data = $filter('filter')($scope.product_detail,condition);
                             equipment_data.forEach(function(eq_item){
                                 machine_data.forEach(function(m_item)
                                 {
                                     if(m_item.machine_no == eq_item.equipment_no)
                                         m_item.dis_order_score += eq_item.good_rate;
                                     if(m_item.dis_order_score > 0)
                                         has_score = true;
                                 });
                             });
                     });
                     machine_data = has_score 
                         ? $filter('orderBy')(machine_data, ['dis_order_score', 'machine_no'], true)
                         : $filter('orderBy')(machine_data, ['machine_no']);   
                     break;
                 case "7":
                     var dis_data = [dis_item];
                     var has_score = false;
                     dis_data.forEach(function(item)
                     {
                         var condition = {op_no:item.op_no,product_no:item.item_no,product_ver:item.item_version};
                         var equipment_data = $filter('filter')($scope.product_detail,condition);
                         equipment_data.forEach(function(eq_item){
                         machine_data.forEach(function(m_item)
                         {
                             if(m_item.machine_no == eq_item.equipment_no)
                                 m_item.dis_order_score += eq_item.equipment_seq;
                             if(m_item.dis_order_score > 0)
                                 has_score = true;
                             });
                         });
                     });
                     machine_data = has_score 
                         ? $filter('orderBy')(machine_data, ['dis_order_score', 'machine_no'])
                         : $filter('orderBy')(machine_data, ['machine_no']);  
                     break;
             }
             return machine_data;
        }
        //撤回
        $scope.confirmRollback = function(){
            $mdDialog.dialog('module/moduleA/program/A02/A02_withdraw_menu.html',withdraw_dialog_controller );
        };
        //撤回開窗 controller
        function withdraw_dialog_controller(dialog)
        {
            var controller = 
            {
                content:{ },
                select_list:[],
                show_data:[],
                select_label:"",
                select_machine_no:$scope.selectMachine.machine_no,
                isRunning:false,
                init:function()
                {
                    dialog.select_list = [
                        {"label":$filter('translate')('A02.with_draw.list_label_0'),"code":"0"},
                        {"label":$filter('translate')('A02.with_draw.list_label_1'),"code":"1"},
                        {"label":$filter('translate')('A02.with_draw.list_label_2'),"code":"2"},
                        {"label":$filter('translate')('A02.with_draw.list_label_3'),"code":"3"}];
                    dialog.content =
                    {
                        need_dispatch_plot_detail:[],
                        dispatch_to:[],
                        work_mode:0,
                        with_draw_mode:dialog.select_list[0].code,
                        dispatch_day:moment($scope.work_date).format('YYYY-MM-DD')
                    };
                    dialog.show_data = [];
                    dialog.isRunning = false;
                    $scope.dispatched_detail.forEach(function(detail){
                        if(detail.checked == 'Y'){
                            if(detail.states != '0'){
                                dialog.isRunning = true;
                            }
                            dialog.show_data.push({
                                plot_no:detail.plot_no,
                                op_name:detail.op_name,
                                op_no:detail.op_no,
                                limit_qty:detail.plot_qty,
                                qty:detail.plot_qty,
                                mo_no:detail.wo_no,
                                uncheck_in_qty:detail.uncheck_in_qty,
                                item_no:detail.item_no,
                                item_name:detail.item_name,
                                item_version:detail.item_version,
                                item_spec:detail.item_spec,
                                mo_no:detail.wo_no,
                                machine_no:$scope.selectMachine.machine_no,
                                plot_start_time:detail.plot_start_time,
                                plot_end_time:detail.plot_end_time
                            });
                        }
                    });
                    dialog.select_label =  dialog.select_list[0].label;
                },
                load_withdraw_list:function()
                {
                    $scope.$root.showSelect({
                        label:"label",
                        code: 'code',
                        selectCode:dialog.select_code,
                        list: dialog.select_list,
                        confirm: function (item,select_dialog) 
                        {
                            if(dialog.content.with_draw_mode != item.code)
                            {
                                //mode change init dialog display qty
                                dialog.show_data.forEach(function(item)
                                {
                                    item.qty = item.limit_qty;
                                });
                            }
                            select_dialog.hide();
                            dialog.select_label = item.label;
                            dialog.content.with_draw_mode =item.code;
                        }
                    });
                },
                checkWithdrawQty:function(event,item)
                {
                    var target = event.currentTarget;
                    angular.element(target).addClass('is-focus');
                    $calculater.open(function(num,dialog)
                    { 
                        angular.element(target).removeClass('is-focus');
                        dialog.hide();
                        if(num > 0 && num <= item.limit_qty)
                            item.qty = num;
                        else
                            $scope.$root.showAlert($filter('translate')('A02.alert.msg1'));
                    },
                    //按下右上角X後會呼叫此function
                    function(dialog)
                    {
                        angular.element(target).removeClass('is-focus');
                        dialog.hide();
                    },
                    {
                        defaultNum : item.qty,
                        decimal : false
                    });
                },
                back: function () 
                {
                    dialog.hide();
                },
                confirm: function () 
                {
                    //20220728 modify by wangzy for 0116240: 派工撤回报错
                    //for循环取值不对，应该取length才对，导致赋值need_dispatch_plot_detail异常
                    for (var i = 0; i < dialog.show_data.length; i++)
                    {
                        dialog.content.need_dispatch_plot_detail.push({
                            plot_no:dialog.show_data[i].plot_no,
                            op_no:dialog.show_data[i].op_no,
                            qty:dialog.show_data[i].qty,
                            mo_no:dialog.show_data[i].mo_no,
                            machine_no:dialog.show_data[i].machine_no,
                            plot_start_time:dialog.show_data[i].plot_start_time,
                            plot_end_time:dialog.show_data[i].plot_end_time
                        });
                    }
                    var _fn = function(){
                        $MMWService.sendToServer({
                            uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                            content : dialog.content,
                            success : function(data){
                                if(data.dispatch_msg && data.dispatch_msg.length > 0)
                                {
                                    var msg = data.dispatch_msg.join("<br>")
                                    $scope.$root.showConfirm(msg, function(confirm_dialog)
                                    {
                                        confirm_dialog.hide();
                                        enforce_dispatch_action(request,function()
                                        {
                                            search({return_type:'110'}, function(){
                                                $scope.$root.showToast(
                                                    $filter('translate')('A02.msg.rollbackSuccess.1')
                                                    + $scope.selectRollback
                                                    + $filter('translate')('A02.msg.rollbackSuccess.2')
                                                );
                                                $scope.Mode = 'MachineExpend';
                                                $scope.selectRollback = 0;
                                                $scope.roll_back_all_bool = false;
                                                $scope.selectMachine.dispatch_size = 0;
                                                var machine = $filter('filter')($scope.machine_detail, {machine_no:$scope.selectMachine.machine_no});
                                                if(machine!=undefined && machine.length > 0){
                                                    $scope.selectMachine = machine[0];
                                                }
                                                initMachineExpend($scope.selectMachine);
                                            });
                                        });
                                    });
                                }
                                else
                                {
                                    search({return_type:'110'}, function(){
                                        $scope.$root.showToast(
                                            $filter('translate')('A02.msg.rollbackSuccess.1')
                                            + $scope.selectRollback
                                            + $filter('translate')('A02.msg.rollbackSuccess.2')
                                        );
                                        $scope.Mode = 'MachineExpend';
                                        $scope.selectRollback = 0;
                                        $scope.roll_back_all_bool = false;
                                        $scope.selectMachine.dispatch_size = 0;
                                        var machine = $filter('filter')($scope.machine_detail, {machine_no:$scope.selectMachine.machine_no});
                                        if(machine!=undefined && machine.length > 0){
                                            $scope.selectMachine = machine[0];
                                        }
                                        initMachineExpend($scope.selectMachine);
                                    });
                                }
                            }
                        });
                    };
                    if(dialog.isRunning)
                    {
                        $scope.$root.showConfirm($filter('translate')('A02.msg.plot_still_running'), function(confirm_dialog){
                            confirm_dialog.hide();
                            dispatch_info_calculation_process(dialog.content, function(data){
                                if(data && data.msg != '')
                                {
                                    $scope.$root.showConfirm(data.msg, function(dialogType){
                                        dialogType.hide();
                                        _fn();
                                    });
                                }
                                else
                                {
                                    _fn();
                                };
                            });
                        });
                    } 
                    else 
                    {
                        _fn();
                    }
                    dialog.hide();
                }
            };
            return controller;
        };
        //取消撤回/移轉
        $scope.cancelRollback = function(){
            $scope.dispatched_detail.forEach(function(detail){
                detail.checked = undefined;
            });
            $scope.selectRollback = 0;
            $scope.Mode = 'MachineExpend';
            $scope.roll_back_all_bool = false;
        };

        //改派
        $scope.confirmTransfer = function(){
            var transferItem,
                feedback = function(data){
                    dispatchItem = transferItem;
                    MachineListMode = '2';//轉移
                    machineList = EquipmentSortForDialogAction(dispatchItem,data);
                    $mdDialog.dialog(
                            'module/moduleA/program/A02/A2_MachineList.tmp.html',
                            MachineListController
                    );
                };
            // 取出勾選的已派生產批
            $scope.dispatched_detail.forEach(function(detail){
                if(detail.checked == 'Y'){
                    transferItem = detail;
                    transferItem.qty = detail.plot_qty;
                    transferItem.machine_no = $scope.selectMachine.machine_no;
                }
            });
            if(transferItem){
                if($scope.isLine == '1')
                    getLineMachineList(transferItem.plot_no, transferItem.op_no, $scope.work_date, feedback);
                else
                    getMachineList($scope.work_date, feedback);
            }
        };

        // 批次合併
        $scope.confirmBatchMerge = function(){
            $mdDialog.dialog(
                'module/moduleA/program/A02/A02_batchMerge.tmp.html', function(dialog){
                    return {
                        batchMerge_input: '',
                        back : function(){
                            dialog.hide();
                        },
                        confirm: function(){
                            var content = {
                                work_mode: 3,
                                dispatch_day: moment($scope.work_date).format('YYYY-MM-DD'),
                                machine_detail: [{
                                    machine_no: $scope.selectMachine.machine_no,
                                    dispatched_detail: []
                                }],
                                need_dispatch_plot_detail:[]
                            };

                            $scope.dispatched_detail.forEach(function(item){
                                if(item.checked == 'Y')
                                {
                                    item.qty = (+item.plot_qty);
                                    item.batch_mark = dialog.batchMerge_input;
                                    content.machine_detail[0].dispatched_detail.push(item);
                                    content.need_dispatch_plot_detail.push(item);
                                }
                            });

                            $MMWService.sendToServer({
                                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                                content : content,
                                success : function(data){
                                    if(data.dispatch_msg && data.dispatch_msg.length > 0)
                                    {
                                        var msg = data.dispatch_msg.join("<br>")
                                        $scope.$root.showConfirm(msg, function(confirm_dialog)
                                        {
                                            confirm_dialog.hide();
                                            enforce_dispatch_action(request,function()
                                            {
                                                dialog.hide();
                                                dialog.batchMerge_input = '';
                                            });
                                        });
                                    }
                                    else
                                    {
                                        dialog.hide();
                                        dialog.batchMerge_input = '';
                                    }
                                    
                                }
                            });
                        }
                    }
                }
            )
        };

        // 刪除批次合併註記
        $scope.deleteBatchMergeMark = function(detail){
            detail.batch_mark = '';
            var content = {
                work_mode: 3,
                dispatch_day: moment($scope.work_date).format('YYYY-MM-DD'),
                machine_detail: [{
                    machine_no: $scope.selectMachine.machine_no,
                    dispatched_detail: [detail]
                }],
                need_dispatch_plot_detail: [detail]
            };
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                content : content,
                success : function(data, response){
                    if(response.isSuccess){
                        // 批次合併註記刪除成功
                        $scope.$root.showToast($filter('translate')('A02.msg.batchMerge_delete_success'));
                    }
                }
            });
        };

        function MachineListConfirmTransfer(dialog){
            var dispatchSum = 0;
            var content = {
                need_dispatch_plot_detail:[dispatchItem],
                dispatch_to:[],
                work_mode:2,
                transfer_day:moment(dialog.work_date).format('YYYY-MM-DD'),//要轉移的目標日期
                dispatch_day:moment($scope.work_date).format('YYYY-MM-DD')//派工當時的日期
            };
            dialog.machineList.forEach(function(machine, index){
                if(machine.inputQty != undefined && machine.inputQty != 0){
                    content.dispatch_to.push({machine_no:machine.machine_no,qty: machine.inputQty});
                    dispatchSum+= (+machine.inputQty);
                }
            });

            var _fn = function(request){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                    content : request,
                    success : function(data){ 
                        //改派以後不會跳日
                        //$scope.work_date = dialog.work_date;
                        if(data.dispatch_msg && data.dispatch_msg.length > 0)
                        {
                            var msg = data.dispatch_msg.join("<br>")
                            $scope.$root.showConfirm(msg, function(confirm_dialog)
                            {
                                confirm_dialog.hide();
                                enforce_dispatch_action(request,function()
                                {   
                                    dialog.hide();
                                    search({return_type:'110'}, function(){
                                        $scope.$root.showToast(dispatchItem.plot_no+$filter('translate')('A02.msg.transSuccess'));
                                        $scope.Mode = 'MachineExpend';
                                        $scope.selectRollback = 0;
                                        $scope.selectMachine.dispatch_size = 0;
                                        var machine = $filter('filter')($scope.machine_detail, {machine_no:$scope.selectMachine.machine_no});
                                        if(machine!=undefined && machine.length > 0){
                                            $scope.selectMachine = machine[0];
                                        }
                                        initMachineExpend($scope.selectMachine);
                                    });
                                });
                            });
                        }
                        else
                        {
                            dialog.hide();
                            search({return_type:'110'}, function(){
                                $scope.$root.showToast(dispatchItem.plot_no+$filter('translate')('A02.msg.transSuccess'));
                                $scope.Mode = 'MachineExpend';
                                $scope.selectRollback = 0;
                                $scope.selectMachine.dispatch_size = 0;
                                var machine = $filter('filter')($scope.machine_detail, {machine_no:$scope.selectMachine.machine_no});
                                if(machine!=undefined && machine.length > 0){
                                    $scope.selectMachine = machine[0];
                                }
                                initMachineExpend($scope.selectMachine);
                            });
                        }
                    }
                });
            };

            if(content.dispatch_to.length == 0){
                //尚未輸入派工數量
                $scope.$root.showAlert($filter('translate')('A02.msg.no_dispatch_qty'));
            } else if(dispatchSum <= dispatchItem.qty){
                dispatch_info_calculation_process(content, function(data){
                    if(data &&  data.suggest_detail && data.suggest_detail.length > 0)
                    {
                        OpenMachineSuggestListDialog(1,content,data.suggest_detail);
                        dialog.hide();
                    }
                    else if(data && data.msg != '')
                    {
                        $scope.$root.showConfirm(data.msg, function(dialogType){
                            dialogType.hide();
                            _fn(content);
                        });
                    }
                    else
                    {
                        _fn(content);
                    };
                });
            } else {
                $scope.$root.showAlert($filter('translate')('A02.msg.transOver') + dispatchItem.qty);
            }
        }

        $scope.dispatchedFilter = function(item){
            return item.states != '0';
        };

        function dispatch_info_get_machine_detail(content, callback){
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_WIP.dispatch_area_info_get',
                content : content,
                success: function(data){
                    if(data.machine_detail && data.machine_detail.length>0)
                        callback(data.machine_detail[0].dispatched_detail);
                    else
                        callback([]);
                }
            });
        }

        function dispatch_info_calculation_process(content, callback){
            $MMWService.sendToServer({
                uri : 'ServicesSTD.Module_WIP.dispatch_info_calculation_process',
                content : content,
                success: function(data){
                    if(callback)
                        callback(data);
                }
            });
        };

        //分頁
        $scope.getPages = function(list, PageConfig, filterItem){
            if(list){
               //console.log();
               if($scope.order_by_mode.name != "")
                list =  $filter('orderBy')(list,$scope.order_by_mode.name,$scope.order_by_mode.sort);
               var temp_list = list.filter(function(item, index, array){
                    var isOK = true,
                        keys = Object.keys(filterItem);
                    for(var i =0; i<keys.length;i++){
                        var key = keys[i];
                        if(isOK && item[key]!=null && filterItem[key] && filterItem[key]!=''){
                            if(item[key].toString().indexOf(filterItem[key]) == -1){
                                isOK = false;
                                break;
                            }
                        }
                    }
                    return isOK;
                });
                if(PageConfig){
                    if(temp_list.length != 0){
                        PageConfig.total_page = Math.ceil(temp_list.length/PageConfig.page_count);

                        if(PageConfig.page >= PageConfig.total_page){
                            PageConfig.page = 0;
                        }
                        var index = PageConfig.page*PageConfig.page_count;
                        return temp_list.slice(index, index+PageConfig.page_count);
                    } else {
                        PageConfig.total_page = 1;
                        PageConfig.page = 0;
                    }
                } else {
                    return temp_list;
                }
            } else {
                
                return list;
            }
        };
        function enforce_dispatch_action(request,feedback)
        {
            request.enforce_dispatch_msg = "1";
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.dispatch_area_info_set_process',
                content : request,
                success : function(data)
                {
                    feedback();
                }
            });
        }
    }
];});
